package com.biostime.qdingding.common.api.sigin;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Enumeration;
import java.util.Set;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import com.biostime.qdingding.common.utils.StringUtils;

public class ApiUtils {
	public static final String DEFAULT_CHARSET = "UTF-8";

	public static Map<String, String> generateApiParams(HttpServletRequest request) {
		TreeMap<String, String> params = new TreeMap<String, String>();
		
		Enumeration<String> paramNames = request.getParameterNames();
		
		while (paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			
			if(StringUtils.isNotEmpty(paramName)){
				String[] paramValues = request.getParameterValues(paramName);
				
				String paramValue = "";
				if (paramValues!=null){
					if (paramValues.length >= 1) {
						paramValue = paramValues[0];
					}
				}
				params.put(paramName.toLowerCase(), paramValue);
			}
		}

		return params;
	}
	
	public static String buildQuery(Map<String, String> params, String charset)
			throws UnsupportedEncodingException {
		if (params == null || params.isEmpty()) {
			return null;
		}
		if (StringUtils.isEmpty(charset)) {
			charset = DEFAULT_CHARSET;
		}

		StringBuilder query = new StringBuilder();
		Set<Entry<String, String>> entries = params.entrySet();
		boolean hasParam = false;

		for (Entry<String, String> entry : entries) {
			String name = entry.getKey();
			String value = entry.getValue();
			// 忽略参数名或参数值为空的参数
			if (!StringUtils.isEmpty(name) && !StringUtils.isEmpty(value)) {
				if (hasParam) {
					query.append("&");
				} else {
					hasParam = true;
				}

				query.append(name).append("=")
						.append(URLEncoder.encode(value, charset));
			}
		}

		return query.toString();
	}
	
	/**
	 * 获取图片URL
	 * @param imgCode 图片Code
	 * @param size 图片尺寸，如：100x100
	 * @param imgPrex 图片后缀名，如：png
	 * @return
	 */
	public static String getImgUrl(String imgCode, String size, String imgPrex){
	    if(imgCode == null || "".equals(imgCode)){
	        return "";
	    }
	    StringBuffer imgUrl = new StringBuffer();
	    imgUrl.append("/AttachFile/rfweb/" + imgCode);
	    if(size != null && size.length() > 0){
	        size = size.toLowerCase();
	        imgUrl.append("_" + size);
	    }
        imgUrl.append("." + imgPrex);
	    return imgUrl.toString();
	}
}
